
#include <phApp_Init.h>
#include "log/log2.h"

#include "reader_samav3.h"
#include "config/config3.h"


int reader_ks_init(void)
{
    return 0;
}

static int reader_get_ks_key_type(uint8_t type){
	switch(type){
		case KEY_T_AES128: return PH_KEYSTORE_KEY_TYPE_AES128;
		case KEY_T_AES192: return PH_KEYSTORE_KEY_TYPE_AES192;
		case KEY_T_AES256: return PH_KEYSTORE_KEY_TYPE_AES256;
		case KEY_T_3DES: return PH_KEYSTORE_KEY_TYPE_2K3DES;
		case KEY_T_3K3DES: return PH_KEYSTORE_KEY_TYPE_3K3DES;
		default: return -1;
	}
}

static int reader_ks_setup_flash(uint8_t kid, uint8_t* ks_id, uint8_t *ks_ver)
{
	key_t key;
	if(config3_get_key(kid & ~ KID_FLASH_MASK, &key)){
		return -1;
	}

	int key_type = reader_get_ks_key_type(key.type);
	if(key_type < 0){
		return -1;
	}
	void* key_store = phNfcLib_GetDataParams(PH_COMP_KEYSTORE);
	uint8_t ver = 0;
	uint8_t key_no = 1;	
	uint8_t* key_data = key.data;
	
	LOG2_DBG("keyNo: %d, ver: %d, key_no: %d", key_no, ver);
	LOG2_BUF_DBG("key", key_data, 16);
	
	phKeyStore_FormatKeyEntry(key_store, key_no, (uint16_t)key_type);
	phKeyStore_SetKeyAtPos(key_store, key_no, 0, (uint16_t)key_type, key_data, ver);
	*ks_id = key_no;
	*ks_ver = ver;
    return 0;
}
static int reader_ks_setup_sam(uint8_t kid, uint8_t* ks_id, uint8_t *ks_ver){
	typedef struct {
		uint8_t kid;
		uint8_t sam_kid;
		// uint8_t ver;
	}kid_to_sam_kid_ver_t;

	static const kid_to_sam_kid_ver_t kid_to_sam_kid_ver[] = {
		{KID_KFR0, SAM_KID_KFR0},
		{KID_KFR, SAM_KID_KFR},
		{KID_KFM, SAM_KID_KFM},
		{KID_KMR, SAM_KID_KMR},
		{KID_KMM, SAM_KID_KMM},
		{KID_KCR, SAM_KID_KCR},
		{KID_KCM, SAM_KID_KCM},
		{KID_KUR, SAM_KID_KUR},
		{KID_KUM, SAM_KID_KUM},
		{KID_APPLE_PRIV, SAM_KID_APPLE_PRIV},
		{KID_APPLE_CRED, SAM_KID_APPLE_CRED},
		{KID_GOOGLE, SAM_KID_GOOGLE},
		{KID_LEAF, SAM_KID_LEAF},
		{KID_SAMSUNG_PAY, SAM_KID_SAMSUNG_PAY},
		{KID_SW_AWC_APP, SAM_KID_SW_AWC_APP},
		{KID_SW_SDC_READ, SAM_KID_SW_SDC_READ},
		{KID_ACCESS_GRID_APPLE_READ, SAM_KID_ACCESS_GRID_APPLE_READ},
		{KID_ACCESS_GRID_APPLE_PRIVACY, SAM_KID_ACCESS_GRID_APPLE_PRIVACY},
	};

	for(int i = 0; i < sizeof(kid_to_sam_kid_ver)/sizeof(kid_to_sam_kid_ver[0]); i++){
		if(kid_to_sam_kid_ver[i].kid == kid){
			*ks_ver = 1;
			*ks_id = kid_to_sam_kid_ver[i].sam_kid;
			return 0;
		}
	}

	return -1;	
}

int reader_ks_setup(uint8_t kid, uint8_t* ks_id, uint8_t *ks_ver)
{
    if(kid & KID_FLASH_MASK){
		return reader_ks_setup_flash(kid, ks_id, ks_ver);
	}
	else{
		return reader_ks_setup_sam(kid, ks_id, ks_ver);
	}
}


/***********************************************************************************************
*                            End Of File
**********************************************************************************************/

